from ast import TryStar
import random
import os ,time ,sys,json,pathlib
from tkinter import N      
from typing_extensions import runtime
from lamda.client import Device,ScriptRuntime

app_packageName = "com.instagram.android"
jsnmae=["insfrida_test.js","dump_igtntstigonprovider.js"]

def ins_frida(d: Device ,app):
    print("开始注入frida脚本")
    time.sleep(random.randint(1,3))
    js_name = jsnmae[1]
    js_path = os.path.join(os.path.dirname(__file__), js_name)
    if not os.path.exists(js_path):
        print(f"[错误] 脚本文件未找到: {js_path}")
        return
    with open(js_path, "r" , encoding="utf-8") as f:
        js_code =f.read()
        print("开始获取app ID")
        pid = get_pid(d)
    session = d.frida.attach(pid)

    script_str = js_code
    script = session.create_script(script_str)
    script.on('message',on_message)
    script.load()

def on_message(message, _):

    print("==============接收到frida消息===============")
    print(message)
    line =json.dumps(message,ensure_ascii=False)+"\n"
    with open("dumpins.txt", "a", encoding="utf-8") as f:
        f.write(line)
    print(line, end="")
    pass
def get_pid(d):
    """
    获取进程Id
    """
    running_process = d.enumerate_running_processes()
    process = next(x for x in running_process if x.processName == app_packageName)
    pid = process.pid
    return pid

if __name__ == "__main__":
    d =Device("192.168.18.200",65008)
    app =d.application(app_packageName)
    # try:
    #     app.start()
    # except Exception as e:
    #     print("app启动失败")
    # time.sleep(5)
    try:
        ins_frida(d,app)
    except Exception as e:
        print("frida运行错误：" , e)
    sys.stdin.read()